package com.wtwd.campus.service.impl;

import com.wtwd.campus.service.RedisService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author ldaoliang
 * @Date create in 14:34 2021/5/6
 * @Description
 */
@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public Map<Object, Object> getUserMsgByToken(String token) {
        // 拿到对应Token的key
        String userKey = redisTemplate.opsForValue().get(token);
        if(StringUtils.isBlank(userKey)){
            return new HashMap<>();
        }
        // 拿到这个key对应的用户数据
        Map<Object, Object> userMsg = redisTemplate.opsForHash().entries(userKey);
        return userMsg;
    }

    @Override
    public String verifyToken(String token) {
        String key = redisTemplate.opsForValue().get(token);
        if(StringUtils.isBlank(key)){
            return null;
        }
        Map<Object,Object> userMsg = redisTemplate.opsForHash().entries(key);
        if(userMsg == null || !token.equals((String)userMsg.get("current_token"))){
            return null;
        }
        return token;
    }
}
